package com.jzh.cmhSystem.biz.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jzh.cmhSystem.biz.UserService;
import com.jzh.cmhSystem.entity.User;
import com.jzh.cmhSystem.entity.UserAndDetail;
import com.jzh.cmhSystem.mapper.UserMapper;
import com.jzh.cmhSystem.utils.MD5Utils;
import com.jzh.cmhSystem.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserByName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
//        queryWrapper.like(StringUtils.isNotBlank(name), "username", username);
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public int register(String username, String password, int role) {
        //MD5加密
        String md5password = MD5Utils.getMD5String(password);
        User tuser = new User();
        tuser.setUsername(username);
        tuser.setPassword(md5password);
        tuser.setRole(role);
        userMapper.insert(tuser);
        return tuser.getId();
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User tuser = new User();
        tuser.setId(id);
        tuser.setPassword(MD5Utils.getMD5String(newPwd));
        System.out.println(tuser);
        userMapper.updatePwdById(tuser);
    }

    @Override
    public int deleteUserById(UserAndDetail userAndDetail) {
        System.out.println(userAndDetail);
        return userMapper.deleteById(userAndDetail.getUserId());
    }

    @Override
    public void updateById(User user) {
        userMapper.updateById(user);
    }

}
